package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.extend.service.ExtendSysOrgService;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdFlightTest;
import com.ccp.dev.qbdms.model.WQbdFlighttestChild;
import com.ccp.dev.qbdms.model.WQbdTrustPeople;
import com.ccp.dev.qbdms.model.WQbdXhdh;
import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.service.WQbdFlightTestService;
import com.ccp.dev.qbdms.service.WQbdFlighttestChildService;
import com.ccp.dev.qbdms.service.WQbdXhdhService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 飞行试验管理 信息操作处理控制器
 *
 * @author hjx
 * @date 2020-05-07 15:28:26
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "飞行试验管理")
@RequestMapping("/qbdms/wQbdFlightTest")
public class WQbdFlightTestController extends SysBaseController {
    @Resource
    private WQbdFlightTestService wQbdFlightTestService;
    @Resource
    private ProcessRunService processRunService;
    @Resource
    private WQbdFlighttestChildService wQbdFlighttestChildService;
    @Resource
    private WQbdXhdhService wQbdXhdhService;
    @Resource
    private ExtendSysOrgService extendSysOrgService;
    @Resource
    private WCustomColumnsService wCustomColumnsService;

    /**
     * 功能描述: 跳转页面
     *
     * @return: java.lang.String
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "跳转页面", exectype = "页面跳转日志")
    public String viewLists(HttpServletRequest request, ModelMap modelMap) {
        // 配置列相关
        wCustomColumnsService.addCustomCols(request);
        // 型号代号
        List<WQbdXhdh> wQbdXhdhs = wQbdXhdhService.getAll();
        // 当前登录用户
        String currentUserId = ContextUtil.getCurrentUserId();
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        // 返回当前系统等级
        modelMap.put("currentSystemLevel", currentSystemLevel);

        modelMap.put("wQbdXhdhs", JSON.toJSONString(wQbdXhdhs));
        modelMap.put("currentUserId", currentUserId);
        return "wQbdFlightTest/list";
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description = "附带检索条件的分页查询飞行试验管理", detail = "查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        // 默认按照试验时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "f_testdate");
            queryFilter.addFilter("orderSeq", "desc");
        }
        ZhiLiangConst.addQueryFilter(queryFilter);
        // 分页数据
        List<WQbdFlightTest> pageDatas = wQbdFlightTestService.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        // 添加编辑按钮权限控制
        ZhiLiangConst.isDataAllowEdit(pageDatas, false);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "跳转到飞行试验管理新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        // 型号代号
        List<WQbdXhdh> wQbdXhdhs = wQbdXhdhService.getAll();
        modelMap.put("wQbdXhdhs", JSON.toJSONString(wQbdXhdhs));
        return "wQbdFlightTest/add";
    }

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: wQbdFlightTest 保存的对象
     * @return: java.lang.Object
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description = "保存飞行试验管理数据", detail = "<#if isAdd>新增<#else>编辑</#if>飞行试验管理数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdFlightTest wQbdFlightTest) {
        String id = wQbdFlightTest.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd", true);
            //新增操作
            ZhiLiangConst.addCommonFields(wQbdFlightTest);
            result = wQbdFlightTestService.add(wQbdFlightTest);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdFlightTest);
            result = wQbdFlightTestService.update(wQbdFlightTest);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdFlightTestService.getOneById(id), wQbdFlightTest));
        }
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
     * 功能描述: 跳转到详情页面
     *
     * @return: java.lang.String
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description = "跳转到飞行试验管理详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        // 型号代号
        List<WQbdXhdh> wQbdXhdhs = wQbdXhdhService.getAll();
        modelMap.put("wQbdXhdhs", JSON.toJSONString(wQbdXhdhs));
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        String statisticsIsClose = RequestUtil.getString(request, "statisticsIsClose");
        modelMap.put("statisticsIsClose", statisticsIsClose);
        return "wQbdFlightTest/particulars";
    }

    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"id"
     * @return: java.lang.Object
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description = "根据主键id查询飞行试验管理的一条数据", detail = "根据主键id查询飞行试验管理的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdFlightTest wQbdFlightTest = wQbdFlightTestService.getOneById(id);
        List<WQbdFlighttestChild> byMainId = wQbdFlighttestChildService.getByMainId(id);
        wQbdFlightTest.setwQbdFlighttestChildren(byMainId);
        if (null == wQbdFlightTest) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("get.success", wQbdFlightTest);
    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description = "根据主键ID删除飞行试验管理数据", exectype = "删除日志", detail = "删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdFlightTest wQbdFlightTest = wQbdFlightTestService.getOneById(key);
            if (!userId.equals(wQbdFlightTest.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
            if (Objects.nonNull(wQbdFlightTest.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(wQbdFlightTest.getReportStatus())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待上报的数据");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("delete.failure.message");
        }
        int result = wQbdFlightTestService.delByIdArray(id.split(","));
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
     * 功能描述: 跳转到导入页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description = "跳转到飞行试验管理导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdFlightTest/import";
    }

    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @param request
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到转到飞行试验管理导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdFlightTest.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }

    /**
     * 功能描述: 导出飞行试验管理数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping("/exportData")
    @Action(description = "导出飞行试验管理数据信息", detail = "导出飞行试验管理数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        List<WQbdFlightTest> wQbdFlightTests = this.wQbdFlightTestService.queryAll(queryFilter);
        if (wQbdFlightTests.isEmpty()) {
            wQbdFlightTests.add(new WQbdFlightTest());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, wQbdFlightTests, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
     * 导入资源文件
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/importData")
    @ResponseBody
    public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
        List<WQbdXhdh> xhdhList = wQbdXhdhService.getAll();
        Map<String, Object> map = new AbstractImpUtil() {
            @Override
            public ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;
                if ("sumOfMoney".equals(fieldName)) {
                    returnType = new ReturnType();
                    if (null != fieldValue) {
                        returnType.setNewValue(fieldValue.replaceAll(",", ""));
                    }
                } else if ("fFlighttestproblems".equals(fieldName)) {
                    returnType = new ReturnType();
                    if (null != fieldValue) {
                        returnType.setNewValue(fieldValue.replaceAll(",", ""));
                    }
                } else if ("fModelnmae".equals(fieldName)) {
                    // 判断型号是否存在，琳:如果没有这个型号名称或型号代号导入的时间判断不让导入
                    returnType = new AbstractImpUtil.ReturnType();
                    boolean sign = true;
                    for (WQbdXhdh xhdh : xhdhList) {
                        if (xhdh.getfModelname().equals(fieldValue)) {
                            returnType.setNewValue(xhdh.getfModelname());
                            sign = false;
                            break;
                        }
                    }
                    if (sign) {
                        returnType.setMsg("非法的值!");
                    }
                } else if ("fModelsymbol".equals(fieldName)) {
                    // 判断型号是否存在，琳:如果没有这个型号名称或型号代号导入的时间判断不让导入
                    returnType = new AbstractImpUtil.ReturnType();
                    boolean sign = true;
                    for (WQbdXhdh xhdh : xhdhList) {
                        if (xhdh.getfModelcode().equals(fieldValue)) {
                            returnType.setNewValue(xhdh.getfModelcode());
                            sign = false;
                            break;
                        }
                    }
                    if (sign) {
                        returnType.setMsg("非法的值!");
                    }
                }
                return returnType;
            }
        }.reverseModels(excelEntity, WQbdFlightTest.class);
        String msg = map.get("msg").toString();
        List<WQbdFlightTest> list = (List<WQbdFlightTest>) map.get("instList");
        if (StringUtil.isEmpty(msg)) {
            this.wQbdFlightTestService.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("dataSource.importXml.success");
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail(msg);
        }
    }

    /**
     * 功能描述: 跳转至modify页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/modify")
    @Action(description = "跳转到飞行试验管理modify页面")
    public String viewModify(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        return "wQbdFlightTest/modify";
    }

    /**
     * 功能描述: 跳转至detail页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/detail")
    @Action(description = "跳转到飞行试验管理detail页面")
    public String viewDetail(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        return "wQbdFlightTest/detail";
    }

    /**
     * 功能描述: 启动流程
     */
    @PostMapping("/run")
    @ResponseBody
    @Action(description = "启动飞行试验管理流程", detail = "启动流程<#if success>成功<#else></#if>")
    public Object run(HttpServletRequest request, @RequestBody WQbdFlightTest wQbdFlightTest) {
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        //实体主键
        String id = wQbdFlightTest.getId();
        int isList = RequestUtil.getInt(request, "isList", 1);
        ProcessCmd processCmd = new ProcessCmd();
        //流程Key
        processCmd.setModelKey("test");
        processCmd.setUserAccount(sysUser.getAccount());
        try {
            if (StringUtil.isNotEmpty(id)) {
                if (isList == 1) {
                    wQbdFlightTest = wQbdFlightTestService.getOneById(id);
                }
                processCmd.setBusinessKey(id);
                processRunService.startProcess(processCmd);
                wQbdFlightTestService.update(wQbdFlightTest);
            } else {
                String genId = ProjectUUIDUtils.getUUIDFor32();
                processCmd.setBusinessKey(genId);
                wQbdFlightTest.setId(genId);
                String tenantId = ContextUtil.getCurrentUserTenantId();
                processRunService.startProcess(processCmd);
                wQbdFlightTestService.add(wQbdFlightTest);
            }
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("flow.start.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("flow.start.failure");
        }
    }

    /**
     * 查询上报的信息
     *
     * @param request
     * @param id
     * @param tableName
     * @return
     */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(HttpServletRequest request, @RequestParam("id") String id, @RequestParam("tableName") String tableName) throws IllegalAccessException {
        //业务数据
        List<WQbdFlightTest> reportList = wQbdFlightTestService.reportList(id, tableName);
        ZhiLiangConst.showName(reportList);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }

}
